package com.traffic.between.config;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;
	private String encoding;
	private boolean forceEncoding;

	public CharacterEncodingFilter() {
		this.forceEncoding = false;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}

	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if ((this.encoding != null) && (((this.forceEncoding) || (request.getCharacterEncoding() == null)))) {
			request.setCharacterEncoding(this.encoding);
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}
		filterChain.doFilter(request, response);
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		if ((!(request instanceof HttpServletRequest)) || (!(response instanceof HttpServletResponse))) {
			throw new ServletException("OncePerRequestFilter just supports HTTP requests");
		}
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		doFilterInternal(httpRequest, httpResponse, filterChain);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		setEncoding(filterConfig.getInitParameter("encoding"));
		setForceEncoding(Boolean.parseBoolean(filterConfig.getInitParameter("forceEncoding")));
	}
}